﻿using EShop.Net.Configuration;
using EShop.Net.Loging;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using NLog;
using System;
using System.Text;

namespace EShop.Net.Auth
{
    /// <summary>
    /// JWT启动服务
    /// </summary>
    public static class AuthorizationSetup
    {
        /// <summary>
        /// 配置属性
        /// </summary>
        private static IConfiguration configuration;

        public static IConfiguration Configuration { get => configuration; set => configuration = value; }

        public static void AddAuthorizationSetup(this IServiceCollection services, string contentPath)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            try
            {
                string Path = "appsettings.json";
                Configuration = new ConfigurationBuilder().SetBasePath(contentPath).Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true }).Build();

                //读取配置文件
                string symmetricKeyAsBase64 = AppSettingsConstVars.JwtConfigSecretKey;
                var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
                SymmetricSecurityKey signingKey = new SymmetricSecurityKey(keyByteArray);
                string issuer = AppSettingsConstVars.JwtConfigIssuer;
                string audience = AppSettingsConstVars.JwtConfigAudience;

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,  // 是否验证Issuer
                    ValidateAudience = true,  // 是否验证Audience
                    ValidateLifetime = true,  // 是否验证失效时间
                    ValidateIssuerSigningKey = true,  // 是否验证SecurityKey
                    ValidAudience = audience,
                        ValidIssuer = issuer,
                        IssuerSigningKey = signingKey
                    };
                });
            }
            catch (Exception ex)
            {
                NLogUtil.WriteAll(LogLevel.Error, LogType.Setup, "JWT启动服务", "AddAuthorizationSetup JWT启动服务", ex);
            }
        }
    }
}
